#include <SDL.h>
#include <fstream>
#include <iostream>
#include <thread>
#ifdef main
#undef main
#endif
using namespace std;
using namespace chrono;
void AudioCallback(void *userdata, // 用户传递的数据
                   Uint8 *stream, int len) {
  cout << "11" << endl;
  SDL_memset(stream, 0, len);
  ifstream *s = (ifstream *)userdata;
  s->read((char *)stream, len);
  if (s->gcount() <= 0) {
    cout << "end";
    // SDL_QuitSubSystem(SDL_INIT_AUDIO);
    SDL_PauseAudioDevice(1, 1);
  }
}

int main(int argc, char **argv) {
  cout << argv[0] << std::endl;
  // 初始化音频模块
  int ret = SDL_Init(SDL_INIT_AUDIO);
  if (ret != 0) {
    std::cerr << SDL_GetError() << std::endl;
    return ret;
  }
  SDL_AudioSpec spec;
  spec.freq = 44100;
  spec.format = AUDIO_S16SYS; // 音频样本类型，使用系统字节序
  spec.channels = 2;          // 音频通道数量
  spec.silence = 0;           // 表示静音时的值
  spec.samples = 1024; // 采样率，用于分割平片模式的多通道数据，例如：sample =
                       // 8，那么LLLLLLLLRRRRRRRR
  spec.callback = AudioCallback;
  ifstream ifs("test_pcm.pcm", std::ios::binary);
  if (!ifs) {
    std::cerr << "ifs.open failed" << endl;
    return -1;
  }
  spec.userdata = &ifs;

  if (SDL_OpenAudio(&spec, nullptr) < 0) {
    std::cerr << "SDL_OpenAudio failed!" << SDL_GetError() << std::endl;
    return -1;
  }
  // 播放
  SDL_PauseAudioDevice(1, 0);
  while (ifs.eof() == false) {
    SDL_Delay(100);
  }
  SDL_Quit();
  SDL_QuitSubSystem(SDL_INIT_AUDIO);
  return 0;
}
